import Taro, { Component } from '@tarojs/taro'
import { Image, View } from '@tarojs/components'
import './index.scss'
import { uploadReply } from "@/api/uploadApi"

const MAX_LIMIT = 9
const verifyMaxLimit = list => {
  return (MAX_LIMIT - list.length) > 0
}

interface IProps {
  list: any
  onChange: Function
}

export default class Index extends Component<IProps, {}> {
  state: any
  props: any

  static options = {
    addGlobalClass: true
  }

  constructor () {
    super(...arguments)
    this.state = {
      imageList: []
    }
  }

  componentWillReceiveProps(nextProps) {
    const { list=[] } = nextProps
    this.setState({
      imageList: list
    })
  }

  //  选择图片
  async onChooseImage() {
    const { imageList } = this.state
    if (!verifyMaxLimit(imageList)) {
      Taro.showToast({ icon: 'none', title: '已超出上传最大数量' })
      return
    }
    const _this = this
    Taro.chooseImage({
      count: MAX_LIMIT - imageList.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        _this.uploadImage(res.tempFiles)
        // _this.uploadImage(res.tempFilePaths)
      },
      fail: function (err) {
        console.log(err)
      }
    })
  }

  //  上传图片
  async uploadImage(list) {
    const { onChange } = this.props
    const { imageList } = this.state
    Taro.showLoading({ title: '请稍后', mask: true })
    for (let i = 0; i < list.length; i++) {
      const resData:any = await uploadReply(list[i]['originalFileObj'])
      imageList.push(resData.data.accessUrl)
    }
    this.setState({
      imageList
    }, () => {
      onChange(imageList)
      Taro.hideLoading()
    })
  }

  //  查看图片
  onSeeImage (key, urls) {
    wx.previewImage({ current: urls[key], urls })
  }

  //  删除图片
  onRemoveImage (key, imageList) {
    const { onChange } = this.props
    imageList.splice(key, 1)
    this.setState({
      imageList
    }, () => {
      onChange(imageList)
    })
  }

  render() {
    const { imageList } = this.state
    return (<View className='image-list comment-img-picker'>
      {imageList.map((img, key) => {
        return (<View key={key} className='image-item'>
          <Image src={img} className='image-item' onClick={this.onSeeImage.bind(this, key, imageList)}/>
          <View className='image-item__remove-btn bnn-icon' onClick={this.onRemoveImage.bind(this, key, imageList)}>&#xe646;</View>
        </View>)
      })}
      {verifyMaxLimit(imageList) && <View className='image-item upload-item thin-border f-g-5 f-d-c' onClick={this.onChooseImage.bind(this)}>
        <View className='upload-icon bnn-icon'>&#xe665;</View>
        <View className='upload-text'>添加图片</View>
      </View>}
   </View>)
  }
}
